package com.visec.hdy.hadoop.proxy;

import java.io.File;
import java.lang.reflect.Method;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class FileStatusProxy implements MethodInterceptor {
	private FileStatus fs;

	public FileStatusProxy(FileStatus fs) {
		this.fs = fs;
	}

	protected String getAbstractPath(Path p) {
		StringBuilder s = new StringBuilder(p.getName());
		Path path = p;
		while (path.getParent() != null && (!"/".equals(path.getParent().getName()))) {
			path = path.getParent();
			s.insert(0, path.getName() + "/");
		}
		return s.toString();
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		if("getName".equals(method.getName())){
			return fs.getPath().getName();
		}
		if ("length".equals(method.getName())) {
			return fs.getLen();
		}
		if ("getPath".equals(method.getName())) {
			return getAbstractPath(fs.getPath());
		}
		if ("toString".equals(method.getName())) {
			return getAbstractPath(fs.getPath());
		}
		throw new UnsupportedOperationException();
	}

	public static File create(FileStatus fs) {
		Enhancer e = new Enhancer();
		e.setSuperclass(File.class);
		e.setCallback(new FileStatusProxy(fs));
		return (File) e.create(new Class[] { String.class }, new Object[] { "" });
	}

}
